<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Workerman\Worker;
use Workerman\Connection\TcpConnection;
use Workerman\Connection\AsyncTcpConnection;
use Workerman\Timer;
use Illuminate\Support\Facades\Log; // 引入 Laravel 的日志系统


class work extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'workerman {action} {--d} {--g}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'start a Workerman server';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $action = $this->argument('action'); // 获取命令中的 action 参数（如 start, stop, reload）
        $isDaemon = $this->option('d'); // artisan 命令规定死了，只能--d的形式来启动
        $isGraceful = $this->option('g');
        global $argv; // php artisan 来运行脚本，array(3) {[0]=>string(7) "artisan"[1]=>string(9) "workerman"[2]=>string(6) "status"}
        $argv[2] = $action;
        if ($isDaemon) { // 以下改为workerman的启动参数
            $argv[3] = '-d';
        } elseif ($isGraceful) {
            $argv[3] = '-g';
        }
        $this->startWorker1(); // 开启1号workerman， 主要处理http类
        $this->startWorker2(); // 开启2号workerman， 主要处理物联网类（tcp，mqtt）
        $this->startWorker3();
        Worker::runAll(); // 统一启动所有的worker
    }

    public function startWorker1()
    {
        $worker = new Worker();
        $worker->count = 4;
        $worker->onWorkerStart = function ($worker) {
            try {
                switch ($worker->id) {
                    case 0: // 捷顺的任务
                        $jieShun = app()->make(\App\Services\JieShunService::class);
                        //$jieShun->test();
                        break;
                    case 1:
                        break;
                    default:
                        break;
                }
            } catch (\Exception $e) {
//                Log::error("An error occurred in Worker_" . $worker->id . ": " . $e->getMessage(), [ // 记录错误日志
//                    'worker_id' => $worker->id,
//                    'exception' => $e,
//                ]);
                echo "An error occurred in Worker_" . $worker->id . ": " . $e->getMessage();
            }
        };
    }

    public function startWorker2()
    {
        $worker = new Worker();
        $worker->count = 4;
        $worker->onWorkerStart = function ($worker) {
            try {
                // 为每个子进程创建独立的 MQTT 客户端实例
                $mqttClient = new \Workerman\Mqtt\Client(env('MQTT_URL'), ['client_id' => "sy-mqtt-client-".mt_rand(), 'username' => env('MQTT_USERNAME'), 'password' => env('MQTT_PASSWORD'), 'protocol_level' => 5]);
                $mqttClient->connect();
                switch ($worker->id) {
                    case 0:
                        app()->make(\App\Services\DeviceModelService::class,  ['mqttClient' => $mqttClient]); // 执行485设备定时采集数据
                        break;
                    case 1:
                        $receive = app()->make(\App\Services\ModelReceiveService::class,  ['mqttClient' => $mqttClient]); // 执行485设备收集数据
                        //$receive->test('507_06', '温度');
                        break;
                    case 2:
                        $worker->protocol = 'Workerman\\Protocols\\Http';
                        break;
                    default:
                        break;
                }
            } catch (\Exception $e) {
//                Log::error("An error occurred in Worker_" . $worker->id . ": " . $e->getMessage(), [ // 记录错误日志
//                    'worker_id' => $worker->id,
//                    'exception' => $e,
//                ]);
                echo "An error occurred in Worker_" . $worker->id . ": " . $e->getMessage();
                echo $e->getFile() . $e->getLine();
            }
        };
    }

    public function startWorker3()
    {
        $worker = new Worker('tcp://0.0.0.0:6800');
        $worker->clients = []; // 初始化客户端连接
        $worker->onConnect = function($connection) {
            echo "新客户端连接\n";
            $key = $connection->getRemoteIp() . ':' . $connection->getRemotePort();
            $this->clients[$key] = $connection;
        };
        $worker->onClose = function($connection) {
            echo "客户端断开连接\n";
            $key = $connection->getRemoteIp() . ':' . $connection->getRemotePort();
            if (isset($this->clients[$key])) {
                unset($this->clients[$key]);
            }
        };
        $worker->onMessage = function($connection, $data) {
            var_dump(array_keys($this->clients));
            // 处理接收到的数据
            $message = "收到客户端数据：{$data}" . "客户端ip:{$connection->getRemoteIp()}" . "客户端端口：{$connection->getRemotePort()}" ;
            //echo $message . PHP_EOL;
            //if ($connection->getRemoteIp() == '192.168.1.11' && strstr($data,'beat')) {
                // 发送数据给客户端
                //var_dump($connection->getRemotePort());
                //$connection->send(0000);
                //var_dump($connection);
            //}


        };
    }
}
